package com.onlineMIS.action.headQ.inventory;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import net.sf.json.JSONObject;

import com.onlineMIS.ORM.DAO.Response;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.HeadQTagDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.barCodeGentor.HeadQTagGroupDaoImpl;
import com.onlineMIS.ORM.DAO.headQ.inventoryFlow.HeadQInventoryStoreDAOImpl;
import com.onlineMIS.ORM.DAO.headQ.user.UserInforDaoImpl;
import com.onlineMIS.ORM.entity.headQ.SQLServer.ClientsMS;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTag;
import com.onlineMIS.ORM.entity.headQ.barcodeGentor.HeadQTagGroup;
import com.onlineMIS.ORM.entity.headQ.inventory.ImgDetailsVO;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrder;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderProduct;
import com.onlineMIS.ORM.entity.headQ.inventory.InventoryOrderVO;
import com.onlineMIS.ORM.entity.headQ.inventoryFlow.HeadQInventoryStore;
import com.onlineMIS.ORM.entity.headQ.user.UserInfor;
import com.onlineMIS.action.chainS.vo.ChainProductBarcodeVO;
import com.onlineMIS.common.Common_util;
import com.onlineMIS.common.loggerLocal;
import com.opensymphony.xwork2.ActionContext;

public class InventoryOrderJSPAction  extends InventoryOrderAction {
	
	@Autowired
	private HeadQInventoryStoreDAOImpl hStoreDAOImpl;
	@Autowired
	private UserInforDaoImpl userInforDaoImpl;

	//销售单据模板
	private final String saleTemplate = "HqSaleTemplate.xls";
	
	/**
	 * 会计继续修改单据
	 * @return
	 * @throws Exception 
	 */
	public String acctUpdate() throws Exception{
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		
		int orderId = formBean.getOrder().getOrder_ID();
		String uuid = Common_util.getUUID();
		String log = logInventory("acctUpdate", formBean.getOrder().getClient_id(), orderId, uuid);
		loggerLocal.info(log);

		Response response = new Response();
		
		try {
		    response = inventoryService.loadOrder(orderId, loginUserInfor);
		} catch (Exception e) {
			response.setQuickValue(Response.FAIL, "发生错误 : " + e.getMessage());
			loggerLocal.error(e);
		}
		
		int returnCode = response.getReturnCode();

		loggerLocal.infoR(log + "," + returnCode);
		
		if (returnCode != Response.SUCCESS){
			addActionError(response.getMessage());
			return "search";
		} else {
			InventoryOrder order = (InventoryOrder)response.getReturnValue();
			uiBean = inventoryService.prepareUIBean();
			formBean.setOrder(order);
			return "edit";
		}
	}
	
	/**
	 * 处理inventory order的通用接口，根据数据库判断当前order状态然后做出适当判断
	 * 1: edit
	 * 2. display
	 * @return
	 * @throws Exception 
	 */
	public String loadOrder() throws Exception{
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		
		int orderId = formBean.getOrder().getOrder_ID();
		String uuid = Common_util.getUUID();
		String log = logInventory("loadOrder", "-", orderId, uuid);
		loggerLocal.info(log);
		
		Response response = new Response();
		
		try {
		    response = inventoryService.loadOrder(orderId, loginUserInfor);
		} catch (Exception e) {
			response.setQuickValue(Response.FAIL, "发生错误 : " + e.getMessage());
			loggerLocal.error(e);
		}
		
		int returnCode = response.getReturnCode();
		int action = response.getAction();
		
		loggerLocal.infoR(log);
		if (returnCode != Response.SUCCESS){
			addActionError(response.getMessage());
			return ERROR;
		} else {
			InventoryOrder order = (InventoryOrder)response.getReturnValue();
			String nComment = order.getComment().replaceAll("\n", "");
			String nComment2 = order.getComment2().replaceAll("\n", "");
			order.setComment(nComment);
			order.setComment2(nComment2);
			formBean.setStore(order.getStore());
			switch (action) {
				case 1:
					uiBean = inventoryService.prepareUIBean();
					formBean.setOrder(order);
					return "edit";
				case 2:
					formBean.setOrder(order);
					return "retrieveSuccess";						
				default:
					addActionError("无法找到对应页面");
					return ERROR;
			}
		}
	}
	
	

	/**
	 * 为用户预览单据功能，防止用户没有这个单子权限无法查看单据。
	 * @return
	 */
	public String previewOrder(){
		int orderId = formBean.getOrder().getOrder_ID();
		String uuid = Common_util.getUUID();
		String log = logInventory("previewOrder", formBean.getOrder().getClient_id(), orderId, uuid);
		loggerLocal.info(log);
		
	    Response response = new Response();
		
		try {
		    response = inventoryService.previewOrder(orderId);
		} catch (Exception e) {
			response.setQuickValue(Response.FAIL, "发生错误 : " + e.getMessage());
			loggerLocal.error(e);
		}
		
		if (response.isSuccess()) {
		    formBean.setOrder((InventoryOrder)response.getReturnValue());
		    return "preview";
		} else 
			return "error";
	}
	
	/**
	 * pre create the new inventory sales order
	 * @return
	 * @throws Exception 
	 */
	public String create() throws Exception{
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		
		String uuid = Common_util.getUUID();
		String log = logInventory("create", formBean.getOrder().getClient_id(), formBean.getOrder().getOrder_ID(), uuid);
		loggerLocal.info(log);
		
		uiBean = inventoryService.prepareUIBean();
		
		formBean.getOrder().setOrder_Keeper(loginUserInfor);
		formBean.getOrder().setOrder_type(InventoryOrder.TYPE_SALES_ORDER_W);
		formBean.getOrder().setOrder_Status(InventoryOrder.STATUS_INITIAL);

		loggerLocal.infoR(log);
		return "newOrder";
	}
	
	
	/**
	 * pre create the new inventory sales return order
	 * @return
	 * @throws Exception 
	 */
	public String createReturnOrder() throws Exception{
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		String uuid = Common_util.getUUID();
		String log = logInventory("createReturnOrder", formBean.getOrder().getClient_id(), formBean.getOrder().getOrder_ID(), uuid);
		loggerLocal.info(log);
		
		uiBean = inventoryService.prepareUIBean();
		
		formBean.getOrder().setOrder_Keeper(loginUserInfor);
		formBean.getOrder().setOrder_type(InventoryOrder.TYPE_SALES_RETURN_ORDER_W);
		
		loggerLocal.infoR(log);
		return "newOrder";
	}
	
	/**
	 * pre create the new inventory sales return order
	 * @return
	 * @throws Exception 
	 */
	public String createFreeOrder() throws Exception{
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		String uuid = Common_util.getUUID();
		String log = logInventory("createReturnOrder", formBean.getOrder().getClient_id(), formBean.getOrder().getOrder_ID(), uuid);
		loggerLocal.info(log);
		
		uiBean = inventoryService.prepareUIBean();
		
		formBean.getOrder().setOrder_Keeper(loginUserInfor);
		formBean.getOrder().setOrder_type(InventoryOrder.TYPE_SALES_FREE_ORDER_W);
		
		loggerLocal.infoR(log);
		return "newOrder";
	}
	
	public String preSearch(){		
		
		String uuid = Common_util.getUUID();
		String log = logInventory("preSearch", "-", "-", uuid);
		loggerLocal.info(log);

		uiBean = inventoryService.preparePreSearchUIBean();
		
		loggerLocal.infoR(log);
		return "search";
	}


	/**
	 * get the PDA draft orders
	 */
	public String getPDADrafts(){
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		String uuid = Common_util.getUUID();
		String log = logInventory("getPDADrafts","-", "-", uuid);
		loggerLocal.info(log);
		
		List<InventoryOrder> inventoryOrders = inventoryService.getPDADrafts(loginUserInfor);
		
		if (inventoryOrders != null)
			uiBean.setOrders(inventoryOrders);
		
		loggerLocal.infoR(log);
		
		return "pdaDraftList";
	}
	
	/**
	 * get the particular PDA draft order by id
	 */
	public String getPDADraft(){
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		String uuid = Common_util.getUUID();
		String log = logInventory("getPDADraft", "-", formBean.getOrder().getOrder_ID(), uuid);
		loggerLocal.info(log);
		
		InventoryOrder inventoryOrder = inventoryService.getPDADraft(loginUserInfor, formBean.getOrder().getOrder_ID());
		
		String clientName = inventoryOrder.getClient_name();
		if (clientName.indexOf(",") != -1)
			clientName = clientName.split(",")[0];
		
		formBean.setOrder(inventoryOrder);
		Map<Integer, String> clientMap = new HashMap<Integer, String>();
		clientMap.put(inventoryOrder.getClient_id(), clientName);
		formBean.setClientMap(clientMap);
		
		loggerLocal.infoR(log);
		return "pdaOrder";
	}
	

	
	public String createPDAOrder(){
		String uuid = Common_util.getUUID();
		String log = logInventory("createPDAOrder", "-", "-", uuid);
		loggerLocal.info(log);
		
		return "pdaOrder";
	}
	
	/**
	 * pre upload the file
	 * @return
	 */
	public String preUploadFile(){
		return "preUpload";
	}

	private String logInventory(String action, Object clientId, Object orderId, String uuid){
		return super.logInventory(this.getClass().getSimpleName() , action, clientId, orderId, uuid);		
	}
	
	
	/**
	 * 下载销售报表
	 * @return
	 */																					
	public String downloadSaleInfo() {
		loggerLocal.info(this.getClass().getName() + ".downloadFinanceCategory");
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
				.get(ServletActionContext.HTTP_REQUEST);
		String contextPath = request.getRealPath("/");
		Response response = new Response();
		try {
			String sort = "startTime";
			String order = "desc";
			List<InventoryOrder> orderList = inventoryService.search(formBean,sort,order);
			List<InventoryOrderVO> list  = (List<InventoryOrderVO>) inventoryService.constructInventoryOrderVOMap(orderList, loginUserInfor).get("rows");
			response = inventoryService.generateHqSaleExcel(contextPath + "WEB-INF\\template\\" + saleTemplate,list);
		} catch (Exception e) {
			response.setReturnCode(Response.FAIL);
			response.setMessage(e.getMessage());
		}

		if (response.getReturnCode() == Response.SUCCESS) {
			InputStream excelStream = (InputStream) response.getReturnValue();
			formBean.setFileStream(excelStream); 
			formBean.setFileName(saleTemplate);
			return "download";						
		} else
			return ERROR;
	}
	
	/**
	 * 库房登录后获取PDA选货单据
	 * @return
	 */
	public String getPDAOrder4StoreMB() {
		loggerLocal.info(this.getClass().getName() + ".getPDAOrder4StoreMB");
		UserInfor loginUserInfor = (UserInfor)ActionContext.getContext().getSession().get(Common_util.LOGIN_USER);

		Response response = inventoryService.getPDAOrder4StoreMB(formBean, loginUserInfor,0);
		
		return ERROR;
	}

}
